package com.kingkim.electromechanical.usercenter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kingkim.electromechanical.commonutils.model.PageBean;
import com.kingkim.electromechanical.usercenter.model.po.Role;
import com.kingkim.electromechanical.usercenter.model.po.User;
import com.kingkim.electromechanical.usercenter.model.vo.UserView;
import com.kingkim.electromechanical.usercenter.service.ILoginService;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("login")
public class LoginController {

    /**
     * 日志
     */
    private static final Logger log = Logger.getLogger(LoginController.class);

    @Resource
    private ILoginService loginService;

    /**
     * 查询所有用户的方法
     */
    @RequestMapping("query")
    public @ResponseBody
    String QueryForList(@ModelAttribute User user, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "12") int limit) {
        String JSONString = null;
        try {
            Map<String, Object> map = new HashMap();
            PageBean<UserView> p = loginService.QueryForList(page, limit, user);
            map.put("data", p.getList());
            map.put("code", 0);
            map.put("msg", "success");
            map.put("count", p.getTotalCount());
            JSONString = JSON.toJSONString(map);
        } catch (Exception e) {
            log.error("查询用户列表异常：" + e.getMessage());
        }
        return JSONString;
    }


    @RequestMapping("delete")
    public @ResponseBody
    String DeleteForList(@RequestParam("ids") String idJSON) {
        String JSONString = null;
        try {
            List<String> ids = JSONArray.parseArray(idJSON, String.class);
            int flat = loginService.DeleteForList(ids);
            Map map = new HashMap<String, Object>();
            map.put("result", flat);
            JSONString = JSON.toJSONString(map);
        } catch (Exception e) {
            log.error("删除用户信息异常:" + e.getMessage());
        }
        return JSONString;
    }


    @RequestMapping("save")
    public @ResponseBody
    String SaveOrModify(@ModelAttribute User user) {
        Map map = new HashMap<String, Object>();
        try {
            int flat = loginService.SaveOrModify(user);
            map.put("result", flat);
        } catch (Exception e) {
            log.error("保存用户信息异常:" + e.getMessage());
        }
        return JSON.toJSONString(map);
    }
}

